<?php
namespace App\Http\Controllers\Exp;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Components\Tools;
use App\Components\DyToools;
use App\Models\DyModels\Douyin;
use App\Models\ExpModels\Exp;
class IndexController extends Controller{
    /**
	*	爆款码管理模块
	*/
	
	public function __construct(Request $request) {
		$this->parames = $request->all();
		$this->scope="video.create,video.delete,video.data,video.list,user_info,renew_refresh_token,mobile_alert,mobile,data.external.item";
		$this->clientKey=Tools::getOneconfig("/config/third.json",array('douyin','dy_client_key'));
		$this->clientSecret=Tools::getOneconfig("/config/third.json",array('douyin','dy_client_secret'));
		$this->url=Tools::getOneconfig("/config/third.json",array('douyin','dy_url'));
		$this->quUrl=Tools::getOneconfig("/config/third.json",array('qiniu','qnUrl'));
	}
	
	//返回json 提示数据
	protected function returnJson($code,$msg,$url="",$data=array()){
		exit(json_encode(array('code'=>$code,'msg'=>$msg,'data'=>$data,'url'=>$url)));
	}
	
	//爆款码扫码授权回调接口
	function banck(){
		$Douyin=new Douyin();
		// $date=$this->parames;
		$code=isset($this->parames['code']) ? $this->parames['code'] : '';
		$kid=isset($this->parames['state']) ? intval($this->parames['state']) : 0;//活动ID
		if($kid==0){echo "参数错误";exit;}
		$url=$this->url."/oauth/access_token?client_key={$this->clientKey}&client_secret={$this->clientSecret}&grant_type=authorization_code&code={$code}";
		$data=$this->getJson($url);
		if($data['data']['error_code']==0){
			$re=$this->getUserInfo($data['data']['open_id'],$data['data']['access_token'],$kid);//获取授权信息
			if($re){
			    //存入授权token信息
				$Douyin->saveToken($data['data'],$this->scope,$data['data']['open_id'],$kid);
				//跳转到H5 活动当前指定活动页面 $url是活动链接
				// print_r($date);print_r($kid);print_r($code);//kid和code都有
				//$url=$_SERVER[' ']."/exp/h5view";
				$url="https://www.baidu.com/";
				$pt=555;
                return redirect('https://www.baidu.com/?id='.$pt);
			}else{
				echo "授权失败";
			}
		}else{//抖音返回数据
			echo $data['data']['description'];
		}
	}
	//获取授权用户信息
	function getUserInfo($open_id,$access_token,$kid){
		$Exp=new Exp();
		$url=$this->url."/oauth/userinfo?open_id={$open_id}&access_token={$access_token}";
		$data=$this->getJson($url);
		if($data['data']['error_code']==0){
			$pid=$Exp->selPid($kid);
			return $Exp->saveUserInfo($data['data'],$open_id,$pid,$kid);
		}
		return false;
	}
	//获取回调函数带的数据的相对于卡卷数据
    function getCardinfo($kid){
        $Exp=new Exp();
        $result=$Exp->getCarddata($kid);
    }
	//领取卡券
	function receiveCard(){
		$Exp=new Exp();
		$expId=isset($this->parames['expId']) && intval($this->parames['expId']) ? intval($this->parames['expId']) : 0;
		$open_id=isset($this->parames['open_id']) && $this->parames['open_id'] ? $this->parames['open_id'] : '';
		$access_token=isset($this->parames['access_token']) && $this->parames['access_token'] ? $this->parames['access_token'] : '';
		// print_r($this->parames['open_id']);exit();
		
		$list=$Exp->selPid($expId,"parnterId,videoId,cardId,staTime,endTime");
		$list ? '' : exit('该活动未开启');//$this->returnJson(1,'该活动已过期');
		
		//查询是否无卡券 活动时间内
		if( $list['staTime']>date('Y-m-d H:i:s') ){
			exit('活动未开始');//$this->returnJson(1,'活动未开始');
		}elseif( $list['endTime']<date('Y-m-d H:i:s') ){
			exit('活动已结束');//$this->returnJson(1,'活动已结束');
		}elseif( !$list['cardId'] ){
			//上传视频
			$url=$_SERVER[' ']."/exp/createVideo";
			$this->postUrl($url,['open_id'=>$open_id,'expId'=>$expId,'access_token'=>$access_token]);
			exit('传播成功');//$this->returnJson(0,'传播成功');
		}
		
		//查询是否是可领取的卡券
		$checkAct=$Exp->checkAct($expId);
		$checkAct ? '' : exit('该活动已过期');//$this->returnJson(1,'该活动已过期');
		if($checkAct && $checkAct!=1){
			exit($rescheck);//$this->returnJson(1,$checkAct);
		}
		
		// 加入核销码(随机数字 目前设置10位应该)
        $Writeoff=$this->getCardsPwd(10);
		
		// 卡券入库信息
		$data=[
		    'writeoff'=>$Writeoff,
			'parnterId'=>$list['parnterId'],
			'videoId'=>$list['videoId'],
			'createTime'=>date('Y-m-d'),
		];
		$re=$Exp->saveUcard($data,$open_id,$expId,$list['cardId']);
		if($re==-99){
			exit();//$this->returnJson(1,'你已经领取过该卡券');
		}elseif($re > 0){
			//上传视频
			$url=$_SERVER['HTTP_HOST']."/exp/createVideo";
			$this->postUrl($url,['open_id'=>$open_id,'expId'=>$expId,'access_token'=>$access_token]);
			exit('领取成功');//$this->returnJson(0,'领取成功');
		}else{
			exit('领取失败');//$this->returnJson(1,'领取失败');
		}
	}
    /**
     * 获取随机字符串
     * @param type $length 字符串长度
     * @return string 字符串
     */
    public static function getCardsPwd($length){
        $str = null;
        $strPol = "123456789";
        $max = strlen($strPol)-1;
        for($i=0;$i<$length;$i++){
            $str.=$strPol[rand(0,$max)];
        }
        return $str;
    }
	
	//创建视频
	function createVideo(){
		set_time_limit(0);
        $result = [
            "code" => 0,
            "msg" => '参数错误2',
        ];
        //成功的回调消息
        $successResult = [
            "code" => 1,
            "msg" => '传播成功',
        ];
		$Exp=new Exp();
		$DyToools=new DyToools();
		$body=file_get_contents("php://input");
		$data=json_decode($body,true);
		
		$open_id=isset($data['open_id']) && $data['open_id'] ? $data['open_id'] : exit('open_id错误');
		$access_token=isset($data['access_token']) && $data['access_token'] ? $data['access_token'] : exit('access_token错误');
		$expId=isset($data['expId']) && intval($data['expId']) ? intval($data['expId']) : exit('expId错误');
		
        $open_id=$data['open_id'];
        $access_token=$data['access_token'];
        $expId=$data['expId'];

		//活动信息
		$list=$Exp->selPid($expId,'*');
	    $list ? '' : exit('活动不存在');

		//标题+话题
		$title=$list['title']." ".($list['talk'] ? $list['talk'] : '');
		
		//视频信息
		$video=$Exp->selActivity($list['videoId']);
		//上传封面
		$img_id='';
		if( $video['img'] ){
			$imgUrl=$this->quUrl."/".$video['img'];
			$imgNameList = explode('/', $imgUrl);
			$imgName = isset($imgNameList[1]) ? end($imgNameList) : '';
			$imgList=$DyToools->imageUpload($access_token,$open_id,$imgUrl,$imgName);
			if( isset($imgList['data']['error_code']) && $imgList['data']['error_code']==0 ) {
				$img_id = $imgList['data']['image']['image_id'];
			}
		}
		
		//上传视频
		$video_id='';
		$videoUrl=$this->quUrl."/".$video['url'];
		$videoNameList = explode('/', $videoUrl);
		$videoName = isset($videoNameList[1]) ? end($videoNameList) : '';
		$videoList=$DyToools->videoUpload($access_token,$open_id,$videoUrl,$videoName);
		if( isset($videoList['data']['error_code']) && $videoList['data']['error_code']==0 ) {
			$video_id = $videoList['data']['video']['video_id'];
		}
		//高德poi_id转换
		$postData=false;
		if($list['poiId']){
			$poiList=$DyToools->POI($list['poiId']);
			$postData['poi_id']=!empty($poiList['data']['poi_id']) ? $poiList['data']['poi_id'] : '';
			$postData['poi_name']=!empty($poiList['data']['poi_name']) ? $poiList['data']['poi_name'] : '';
		}
		//@的商户
		if($list['openId']){
			$nickname=$Exp->selName($list['openId']);
			$title.=" @{$nickname}";
			$postData['at_users'][]=$list['openId'];
		}
		//发布视频
		$re=$DyToools->videoCreate($access_token,$open_id,$video_id,$img_id,$title,$postData);
		if( isset($re['extra']['error_code']) && $re['extra']['error_code']==0 ){
			$data=[
				'parnterId'=>$list['parnterId'],
				'img'=>$video['img'],
				'url'=>$video['url'],
				'title'=>$list['title'],
				'talk'=>$list['talk'],
				'open_id'=>$open_id,
				'expId'=>$expId,
				'atOpenid'=>$list['openId'],
				'create_time'=>date('Y-m-d H:i:s'),
				'item_id'=>$re['data']['item_id'],
			];
			$re=$Exp->saveDyVideo($data);
			$re ? exit('视频发布成功') : exit('视频入库失败');
		}
		exit('视频发布失败');
	}
	
	//核销
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	//get请求
	function getJson($url){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
		curl_setopt($ch, CURLOPT_TIMEOUT,60);//连接后等待时间
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);//连接前等待时间
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($ch, CURLOPT_HEADER, FALSE);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);//为true，则会跟踪爬取重定向页面，否则，不会跟踪重定向页面
		curl_setopt($ch, CURLOPT_ENCODING, "");//返回乱码处理
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不验证证书下同
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		$output = curl_exec($ch);
		curl_close($ch);
		return json_decode($output, true);
	}
	
	//异步操作 上传视频
	function postUrl($url,$data){
		//初始化
		$curl = curl_init();
		//设置抓取的url
		curl_setopt($curl, CURLOPT_URL, $url);
		//设置头文件的信息作为数据流输出
		curl_setopt($curl, CURLOPT_HEADER, 0);
		//超时时间
		curl_setopt($curl, CURLOPT_TIMEOUT,60);
		curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 0);//连接前等待时间
		//设置获取的信息以文件流的形式返回，而不是直接输出。
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		//设置post方式提交
		curl_setopt($curl, CURLOPT_POST, 1);
		//设置post数据
		curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //不验证证书下同
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($curl, CURLOPT_HTTPHEADER, array(
			'Content-Type: application/json',
			'Content-Length: ' . strlen(json_encode($data)))
		);

		//执行命令
		$json = curl_exec($curl);
		//关闭URL请求
		curl_close($curl);echo $json;exit;
		return json_decode($json, true);
	}
}